<template>
  <div class="chat-history-container">
    <div class="chat-history-layout">
      <!-- 左侧联系人列表 -->
      <div class="contact-list">
        <div class="contact-header">
          <span>{{ $t('chat.contacts') }}</span>
          <div class="header-actions">
            <el-button type="text" icon="el-icon-plus" @click="showCreateRoomDialog">
              {{ $t('chat.createRoom') }}
            </el-button>
            <el-button type="text" icon="el-icon-connection" @click="showJoinRoomDialog">
              {{ $t('chat.joinRoom') }}
            </el-button>
          </div>
        </div>

        <!-- 联系人类型切换 -->
        <div class="contact-tabs">
          <div class="tab-item" :class="{ 'active': contactType === 'private' }" @click="switchContactType('private')">
            {{ $t('chat.privateChat') }}
          </div>
          <div class="tab-item" :class="{ 'active': contactType === 'group' }" @click="switchContactType('group')">
            {{ $t('chat.groupChat') }}
          </div>
        </div>

        <div v-if="loading" class="loading">
          <i class="el-icon-loading"></i> {{ $t('chat.loading') }}
        </div>
        <div v-else-if="filteredContacts.length === 0" class="no-history">
          {{ contactType === 'private' ? $t('chat.noHistory') : $t('chat.noGroups') }}
        </div>
        <ul v-else class="contact-items">
          <li v-for="(item, index) in filteredContacts" :key="index" class="contact-item"
              :class="{ 'active': selectedContact === (item.roomId || item.username) }" @click="selectContact(item)">
            <div class="contact-avatar">
              <img :src="getAvatar(item.roomName || item.username)" alt="avatar">
              <div v-if="item.roomId" class="group-indicator">群</div>
            </div>
            <div class="contact-info">
              <div class="contact-name">{{ item.roomName || item.username }}</div>
              <div v-if="item.roomId" class="contact-id" @click.stop="copyRoomId(item.roomId)">
                ID: {{ item.roomId }} <i class="el-icon-document-copy"></i>
              </div>
              <div class="contact-time">{{ formatTime(item.lastTime) }}</div>
            </div>
          </li>
        </ul>
      </div>

      <!-- 右侧聊天窗口 -->
      <div class="chat-window">
        <div v-if="!selectedContact" class="no-selection">
          <div class="empty-state">
            <i class="el-icon-chat-dot-round"></i>
            <p>{{ $t('chat.selectContact') }}</p>
          </div>
        </div>
        <div v-else class="chat-content">
          <!-- 聊天头部 -->
          <div class="chat-header">
            <h3>{{ currentChatName }}</h3>
            <div class="header-actions">
              <el-button v-if="isGroupChat" type="text" icon="el-icon-info" @click="showRoomInfo">
                {{ $t('chat.roomInfo') }}
              </el-button>
            </div>
          </div>

          <!-- 聊天消息区域 -->
          <div class="chat-messages" ref="messageContainer">
            <div v-if="messages.length === 0" class="no-messages">
              {{ $t('chat.noMessages') }}
            </div>
            <div v-for="(msg, index) in messages" :key="index" class="message-item"
                 :class="{ 'self': isCurrentUser(msg) }">
              <div class="message-avatar">
                <img :src="getAvatar(getUsernameFromMsg(msg))" alt="avatar">
              </div>
              <div class="message-content">
                <div class="message-name">{{ getUsernameFromMsg(msg) }}</div>
                <div class="message-text">{{ getContentFromMsg(msg) }}</div>
                <div class="message-time">{{ formatTime(msg.createdAt) }}</div>
              </div>
            </div>
          </div>

          <!-- 聊天输入区域 -->
          <div class="chat-input">
            <el-input v-model="messageText" :placeholder="$t('chat.typeSomething')" type="textarea" :rows="3"
                      @keyup.enter.native="sendMessage"></el-input>
            <div class="input-actions">
              <span class="hint">Enter {{ $t('chat.toSend') }}</span>
              <el-button type="primary" @click="sendMessage">{{ $t('chat.send') }}</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建群聊对话框 -->
    <el-dialog :title="$t('chat.createRoom')" :visible.sync="createRoomDialogVisible" width="400px">
      <el-form :model="roomForm" label-width="100px">
        <el-form-item :label="$t('chat.roomName')">
          <el-input v-model="roomForm.roomName"></el-input>
        </el-form-item>
        <el-form-item :label="$t('chat.roomId')">
          <el-input v-model="roomForm.roomId">
            <el-button slot="append" @click="generateRoomId">{{ $t('chat.generate') }}</el-button>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="createRoomDialogVisible = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="createRoom">{{ $t('common.confirm') }}</el-button>
      </span>
    </el-dialog>

    <!-- 加入群聊对话框 -->
    <el-dialog :title="$t('chat.joinRoom')" :visible.sync="joinRoomDialogVisible" width="400px">
      <el-form :model="joinRoomForm" label-width="100px">
        <el-form-item :label="$t('chat.roomId')">
          <el-input v-model="joinRoomForm.roomId"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="joinRoomDialogVisible = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="joinRoom">{{ $t('common.confirm') }}</el-button>
      </span>
    </el-dialog>

    <!-- 群聊信息对话框 -->
    <el-dialog :title="$t('chat.roomInfo')" :visible.sync="roomInfoDialogVisible" width="400px">
      <div v-if="currentRoom">
        <p><strong>{{ $t('chat.roomName') }}:</strong> {{ currentRoom.roomName }}</p>
        <p><strong>{{ $t('chat.roomId') }}:</strong> {{ currentRoom.roomId }}</p>
        <p><strong>{{ $t('chat.createdAt') }}:</strong> {{ formatTime(currentRoom.createdAt) }}</p>
        <p><strong>{{ $t('chat.members') }}:</strong></p>
        <div class="room-members">
          <div v-for="(member, index) in roomMembers" :key="index" class="member-item">
            <img :src="getAvatar(member)" alt="avatar" class="member-avatar">
            <span>{{ member }}</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getChatHistory,
  getChatMessages,
  getMsgList,
  sendMsg,
  createChatRoom,
  joinChatRoom,
  getGreoupMessages,
  getRoomInfo
} from '@/api/msg'
import socket from '@/utils/socket'

export default {
  name: 'ChatHistory',
  data() {
    return {
      loading: true,
      chatHistory: [],
      roomList: [],
      selectedContact: null,
      currentChatName: '',
      isGroupChat: false,
      currentRoom: null,
      roomMembers: [],
      messages: [],
      messageText: '',
      contactType: 'private', // 'private' 或 'group'
      socketConnected: false,
      pollingInterval: null,
      usePolling: false,

      // 创建群聊表单
      createRoomDialogVisible: false,
      roomForm: {
        roomName: '',
        roomId: ''
      },

      // 加入群聊表单
      joinRoomDialogVisible: false,
      joinRoomForm: {
        roomId: ''
      },

      // 群聊信息对话框
      roomInfoDialogVisible: false
    }
  },
  computed: {
    currentUser() {
      return localStorage.getItem('username') || ''
    },
    currentEmail() {
      return localStorage.getItem('email') || ''
    },
    filteredContacts() {
      if (this.contactType === 'private') {
        return this.chatHistory;
      } else {
        return this.roomList;
      }
    }
  },
  mounted() {
    this.loadChatHistory()
    this.loadRoomList()
    this.initSocket()
  },
  watch: {
    // 监听联系人类型变化
    contactType(newVal, oldVal) {
      if (newVal !== oldVal) {
        // 清空当前选中的联系人和消息
        this.selectedContact = null;
        this.currentChatName = '';
        this.isGroupChat = false;
        this.currentRoom = null;
        this.messages = [];
      }
    }
  },
  methods: {
    // 切换联系人类型
    switchContactType(type) {
      if (this.contactType !== type) {
        this.contactType = type;
        // 清空当前选中的联系人和消息
        this.selectedContact = null;
        this.currentChatName = '';
        this.isGroupChat = false;
        this.currentRoom = null;
        this.messages = [];

        // 根据类型重新加载对应的列表数据
        if (type === 'private') {
          this.loadChatHistory();
        } else {
          this.loadRoomList();
        }
      }
    },

    // 初始化Socket连接
    initSocket() {
      if (!socket.connected && this.currentUser) {
        socket.connect()
        socket.emit('join', {username: this.currentUser})

        // 添加连接超时处理
        const connectionTimeout = setTimeout(() => {
          console.warn('Socket 连接超时，启用轮询模式')
          this.startPolling()
        }, 5000)

        // 监听新消息
        socket.on('chat message', (msg) => {
          console.log('收到新消息:', msg)
          // 如果是当前聊天的消息，添加到消息列表
          if (this.isCurrentChatMessage(msg)) {
            this.messages.push(msg)
            this.$nextTick(() => {
              this.scrollToBottom()
            })
          }
        })

        socket.on('connect', () => {
          console.log('Socket 已连接')
          this.socketConnected = true
          clearTimeout(connectionTimeout)
        })

        socket.on('disconnect', () => {
          console.log('Socket 已断开')
          this.socketConnected = false
        })

        socket.on('error', (error) => {
          console.error('Socket 连接错误:', error)
          this.socketConnected = false
        })
      }
    },

    // 判断消息是否属于当前聊天
    isCurrentChatMessage(msg) {
      if (this.isGroupChat) {
        return msg.roomId === this.selectedContact
      } else {
        return (
          (msg.username === this.currentUser && msg.receive === this.selectedContact) ||
          (msg.username === this.selectedContact && msg.receive === this.currentUser)
        )
      }
    },

    // 加载聊天历史记录
    loadChatHistory() {
      const currentUser = this.currentUser
      if (!currentUser) {
        this.loading = false
        return
      }

      // 获取聊天历史记录
      getChatHistory({
        username: currentUser,
        limit: 1000
      })
        .then(res => {
          if (res.meta.status === 200 && res.data) {
            this.chatHistory = res.data
            console.log("聊天历史:", this.chatHistory)
          } else {
            console.error('获取聊天历史失败:', res)
          }
        })
        .catch(err => {
          console.error('获取聊天历史异常:', err)
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 加载群聊列表
    loadRoomList() {
      const currentUser = this.currentUser
      if (!currentUser) {
        return
      }

      // 获取用户加入的群聊列表
      getRoomInfo({
        username: currentUser
      })
        .then(res => {
          if (res.meta.status === 200 && res.data) {
            this.roomList = res.data
            console.log("群聊列表:", this.roomList)
          } else {
            console.error('获取群聊列表失败:', res)
          }
        })
        .catch(err => {
          console.error('获取群聊列表异常:', err)
        })
    },

    // 选择联系人或群聊
    selectContact(contact) {
      if (this.contactType === 'private') {
        this.selectedContact = contact.username
        this.currentChatName = contact.username
        this.isGroupChat = false
        this.loadPrivateMessages(contact.username)
      } else {
        this.selectedContact = contact.roomId
        this.currentChatName = contact.roomName
        this.isGroupChat = true
        this.currentRoom = contact
        this.loadGroupMessages(contact.roomId)
      }
    },

    // 加载私聊消息
    loadPrivateMessages(targetUser) {
      const query = {
        username: this.currentUser, receive: targetUser,
        limit: 1000
      }

      getChatMessages(query).then(res => {
        if (res.meta.status === 200 && res.data) {
          console.log('获取到聊天记录:', res.data)
          this.messages = res.data || []

          this.$nextTick(() => {
            this.scrollToBottom()
          })
        } else {
          console.error('获取聊天记录失败:', res)
          this.messages = []
        }
      }).catch(err => {
        console.error('获取聊天记录异常:', err)
        this.messages = []
      })
    },

    // 加载群聊消息
    loadGroupMessages(roomId) {
      const query = {
        where: {
          roomId: roomId
        },
        order: [['createdAt', 'ASC']], // 按时间升序排序，旧消息在前
        limit: 1000
      }

      getGreoupMessages(query).then(res => {
        if (res.meta.status === 200 && res.data) {
          console.log('获取到群聊记录:', res.data.data)
          this.messages = res.data.data || []

          // 获取群成员
          this.loadRoomMembers(roomId)

          this.$nextTick(() => {
            this.scrollToBottom()
          })
        } else {
          console.error('获取群聊记录失败:', res)
          this.messages = []
        }
      }).catch(err => {
        console.error('获取群聊记录异常:', err)
        this.messages = []
      })
    },

    // 加载群成员
    loadRoomMembers(roomId) {
      getRoomInfo({
        roomId: roomId
      })
        .then(res => {
          if (res.meta.status === 200 && res.data) {
            this.roomMembers = res.data.members || []
          } else {
            console.error('获取群成员失败:', res)
            this.roomMembers = []
          }
        })
        .catch(err => {
          console.error('获取群成员异常:', err)
          this.roomMembers = []
        })
    },
    
    // 复制群聊ID
    copyRoomId(roomId) {
      if (navigator.clipboard) {
        navigator.clipboard.writeText(roomId)
          .then(() => {
            this.$message.success(this.$t('chat.idCopied') || '群聊ID已复制')
          })
          .catch(err => {
            console.error('复制失败:', err)
            this.fallbackCopyRoomId(roomId)
          })
      } else {
        this.fallbackCopyRoomId(roomId)
      }
    },
    
    // 兼容性复制方法
    fallbackCopyRoomId(roomId) {
      const textArea = document.createElement('textarea')
      textArea.value = roomId
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      
      try {
        const successful = document.execCommand('copy')
        if (successful) {
          this.$message.success(this.$t('chat.idCopied') || '群聊ID已复制')
        } else {
          this.$message.error(this.$t('chat.copyFailed') || '复制失败')
        }
      } catch (err) {
        console.error('复制失败:', err)
        this.$message.error(this.$t('chat.copyFailed') || '复制失败')
      }
      
      document.body.removeChild(textArea)
    },

    // 发送消息
    sendMessage() {
      if (!this.messageText.trim()) return

      const msgData = {
        username: this.currentUser,
        email: this.currentEmail,
        content: this.messageText,
        createdAt: new Date().toISOString()
      }

      if (this.isGroupChat) {
        // 群聊消息
        msgData.roomId = this.selectedContact
        msgData.roomName = this.currentChatName
        msgData.isRoom = 1
      } else {
        // 私聊消息
        msgData.receive = this.selectedContact
        msgData.isRoom = 0
      }
      // 发送消息到服务器
      sendMsg(msgData).then(res => {
        if (res.meta.status === 200) {
          console.log('消息发送成功')

          // 添加到本地消息列表
          this.messages.push(msgData)

          // 通过WebSocket发送实时消息
          if (this.socketConnected) {
            socket.emit('chat message', msgData)
            console.log('WebSocket 消息已发送')
          } else {
            console.warn('WebSocket 未连接，无法发送实时消息')
          }

          // 清空输入框
          this.messageText = ''

          // 滚动到底部
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        } else {
          console.error('消息发送失败:', res)
          this.$message.error(this.$t('chat.sendFailed'))
        }
      }).catch(err => {
        console.error('消息发送异常:', err)
        this.$message.error(this.$t('chat.sendFailed'))
      })
    },

    // 显示创建群聊对话框
    showCreateRoomDialog() {
      this.createRoomDialogVisible = true
      this.roomForm = {
        roomName: '',
        roomId: this.generateRoomId()
      }
    },

    // 生成随机房间ID
    generateRoomId() {
      const roomId = 'room_' + Math.random().toString(36).substr(2, 8)
      this.roomForm.roomId = roomId
      return roomId
    },

    // 创建群聊
    createRoom() {
      if (!this.roomForm.roomName || !this.roomForm.roomId) {
        this.$message.warning(this.$t('chat.roomInfoRequired'))
        return
      }

      const roomData = {
        roomName: this.roomForm.roomName,
        roomId: this.roomForm.roomId,
        creator: this.currentUser,
        members: [this.currentUser]
      }

      createChatRoom(roomData).then(res => {
        if (res.meta.status === 200) {

          this.$message.success(this.$t('chat.roomCreated'))
          this.createRoomDialogVisible = false

          // 刷新群聊列表
          this.loadRoomList()

          // 切换到群聊标签
          this.contactType = 'group'
        } else {
          this.$message.error(res.meta.msg || this.$t('chat.createRoomFailed'))
        }
      }).catch(err => {
        console.error('创建群聊异常:', err)
        this.$message.error(this.$t('chat.createRoomFailed'))
      })
    },

    // 显示加入群聊对话框
    showJoinRoomDialog() {
      this.joinRoomDialogVisible = true
      this.joinRoomForm = {
        roomId: ''
      }
    },

    // 加入群聊
    joinRoom() {
      if (!this.joinRoomForm.roomId) {
        this.$message.warning(this.$t('chat.roomIdRequired'))
        return
      }

      const joinData = {
        roomId: this.joinRoomForm.roomId,
        username: this.currentUser
      }

      joinChatRoom(joinData).then(res => {

        if (res.meta.status === 200) {
          this.$message.success(this.$t('chat.roomJoined'))
          this.joinRoomDialogVisible = false

          // 刷新群聊列表
          this.loadRoomList()

          // 切换到群聊标签
          this.contactType = 'group'
        } else if (res.meta.status === 404) {
          this.$message.error(this.$t('chat.roomNotFound'))
        } else if (res.meta.status === 409) {
          this.$message.info(this.$t('chat.alreadyInRoom'))
        } else {
          this.$message.error(res.meta.msg || this.$t('chat.joinRoomFailed'))
        }
      }).catch(err => {
        console.error('加入群聊异常:', err)
        this.$message.error(this.$t('chat.joinRoomFailed'))
      })
    },

    // 显示群聊信息
    showRoomInfo() {
      if (this.isGroupChat && this.currentRoom) {
        this.roomInfoDialogVisible = true
      }
    },

    // 滚动到底部
    scrollToBottom() {
      const container = this.$refs.messageContainer
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    },

    // 判断消息是否来自当前用户
    isCurrentUser(msg) {
      return this.getUsernameFromMsg(msg) === this.currentUser
    },

    // 从消息中获取用户名
    getUsernameFromMsg(msg) {
      if (msg.username) return msg.username
      if (msg.sender) return msg.sender
      if (msg.from_username) return msg.from_username
      return '未知用户'
    },

    // 从消息中获取内容
    getContentFromMsg(msg) {
      if (msg.content) return msg.content
      if (msg.message) return msg.message
      if (msg.messageText) return msg.messageText
      return '无内容'
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      return `${date.getMonth() + 1}/${date.getDate()} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    },

    // 获取头像
    getAvatar(username) {
      if (!username) return ''
      // 简单的头像生成逻辑，实际项目中可以替换为用户真实头像
      return `https://ui-avatars.com/api/?name=${encodeURIComponent(username)}&background=random&color=fff`
    },

    // 启动轮询
    startPolling() {
      if (this.pollingInterval) return

      this.usePolling = true
      console.log('启用轮询模式获取消息')

      this.pollingInterval = setInterval(() => {
        if (this.selectedContact) {
          if (this.isGroupChat) {
            this.loadGroupMessages(this.selectedContact)
          } else {
            this.loadPrivateMessages(this.selectedContact)
          }
        }
      }, 3000) // 每3秒轮询一次
    },

    // 停止轮询
    stopPolling() {
      if (this.pollingInterval) {
        clearInterval(this.pollingInterval)
        this.pollingInterval = null
      }
    }
  },
  beforeDestroy() {
    // 移除所有事件监听
    socket.off('chat message')
    socket.off('connect')
    socket.off('disconnect')
    socket.off('error')
    this.stopPolling()
  }
}
</script>

<style scoped lang="less">
.chat-history-container {
  width: 100%;
  height: 100%;

  .chat-history-layout {
    display: flex;
    height: 700px;
    width: 1000px;
    background: #fff;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    margin: 0 auto;
  }

  .contact-list {
    width: 280px;
    border-right: 1px solid #eaeaea;
    display: flex;
    flex-direction: column;
    background: #f9f9f9;

    .contact-header {
      padding: 15px;
      border-bottom: 1px solid #eaeaea;
      background: #fff;
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        margin: 0;
        font-size: 16px;
        color: #333;
      }

      .header-actions {
        display: flex;

        .el-button {
          padding: 0 5px;
          margin-left: 5px;
        }
      }
    }

    .contact-tabs {
      display: flex;
      border-bottom: 1px solid #eaeaea;

      .tab-item {
        flex: 1;
        text-align: center;
        padding: 10px 0;
        cursor: pointer;
        font-size: 14px;
        color: #666;
        transition: all 0.2s ease;

        &:hover {
          color: #ff6d6d;
        }

        &.active {
          color: #ff6d6d;
          border-bottom: 2px solid #ff6d6d;
          font-weight: bold;
        }
      }
    }

    .loading,
    .no-history {
      padding: 20px;
      text-align: center;
      color: #999;
      font-size: 14px;
      margin-top: 30px;
    }

    .contact-items {
      padding: 0;
      margin: 0;
      list-style: none;
      overflow-y: auto;
      flex: 1;

      .contact-item {
        padding: 12px 15px;
        cursor: pointer;
        display: flex;
        align-items: center;
        transition: all 0.2s ease;
        border-bottom: 1px solid #f0f0f0;

        &:hover {
          background-color: #f0f0f0;
        }

        &.active {
          background-color: #e6f7ff;
          border-right: 3px solid #ff6d6d;
        }

        .contact-avatar {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          overflow: hidden;
          margin-right: 12px;
          position: relative;

          .group-indicator {
            position: absolute;
            right: -2px;
            bottom: -2px;
            background: #ff6d6d;
            color: white;
            font-size: 10px;
            width: 16px;
            height: 16px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 2px solid #f9f9f9;
          }

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .contact-info {
          flex: 1;

          .contact-name {
            font-weight: bold;
            font-size: 14px;
            color: #333;
            margin-bottom: 4px;
          }
          
          .contact-id {
            font-size: 12px;
            color: #909399;
            margin-top: 2px;
            cursor: pointer;
            display: flex;
            align-items: center;
            
            i {
              margin-left: 4px;
              font-size: 14px;
            }
            
            &:hover {
              color: #409EFF;
            }
          }

          .contact-time {
            font-size: 12px;
            color: #999;
          }
        }
      }
    }
  }

  .chat-window {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: #fff;
    overflow: hidden;

    .no-selection {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;

      .empty-state {
        text-align: center;
        color: #999;

        i {
          font-size: 48px;
          margin-bottom: 15px;
          color: #ddd;
        }

        p {
          font-size: 14px;
        }
      }
    }

    .chat-content {
      display: flex;
      flex-direction: column;
      height: 100%;

      .chat-header {
        padding: 15px;
        border-bottom: 1px solid #eaeaea;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: linear-gradient(135deg, #ff6d6d, #ff4f81);
        color: white;
        flex-shrink: 0;

        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: bold;
        }

        .header-actions {
          .el-button {
            color: white;

            &:hover {
              color: rgba(255, 255, 255, 0.8);
            }
          }
        }
      }

      .chat-messages {
        flex: 1;
        padding: 15px;
        overflow-y: auto;
        background: #f9f9f9;
        background-image: linear-gradient(rgba(255, 255, 255, 0.7) 1px, transparent 1px),
        linear-gradient(90deg, rgba(255, 255, 255, 0.7) 1px, transparent 1px);
        background-size: 20px 20px;
        background-position: center center;

        .no-messages {
          text-align: center;
          color: #999;
          margin-top: 30%;
          font-style: italic;
        }

        .message-item {
          display: flex;
          margin-bottom: 18px;
          animation: fadeIn 0.3s ease;

          &.self {
            flex-direction: row-reverse;

            .message-content {
              background: linear-gradient(135deg, #ff6d6d, #ff4f81);
              color: white;
              border-radius: 15px 0 15px 15px;
              margin-left: 0;
              margin-right: 10px;

              .message-name {
                text-align: right;
                color: rgba(255, 255, 255, 0.8);
              }

              .message-time {
                text-align: right;
                color: rgba(255, 255, 255, 0.7);
              }
            }
          }

          .message-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            overflow: hidden;

            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
          }

          .message-content {
            max-width: 70%;
            background: white;
            padding: 12px 15px;
            border-radius: 0 15px 15px 15px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
            margin-left: 10px;

            .message-name {
              font-size: 12px;
              color: #888;
              margin-bottom: 5px;
            }

            .message-text {
              word-break: break-word;
              line-height: 1.4;
              font-size: 14px;
            }

            .message-time {
              font-size: 11px;
              color: #aaa;
              margin-top: 6px;
              text-align: right;
            }
          }
        }
      }

      .chat-input {
        padding: 15px;
        border-top: 1px solid #eaeaea;
        flex-shrink: 0;

        .el-input {
          margin-bottom: 10px;

          /deep/ .el-textarea__inner {
            border-radius: 18px;
            padding: 8px 15px;
            resize: none;
            transition: all 0.3s ease;
            border: 1px solid #e0e0e0;

            &:focus {
              border-color: #ff6d6d;
              box-shadow: 0 0 0 2px rgba(255, 109, 109, 0.2);
            }
          }
        }

        .el-button {
          height: 40px;
          border-radius: 20px;
          padding: 0 20px;
          background: linear-gradient(135deg, #ff6d6d, #ff4f81);
          border: none;
          transition: all 0.3s ease;

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(255, 109, 109, 0.3);
          }

          &:active {
            transform: translateY(0);
          }
        }
      }
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>

<style lang="less">
/* 全局样式，提高对话框z-index */
.el-dialog__wrapper {
  z-index: 3000 !important;
}

.el-dialog {
  margin-top: 15vh !important;
}

.v-modal {
  z-index: 2999 !important;
}

/* 群聊成员样式 */
.room-members {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;

  .member-item {
    display: flex;
    align-items: center;
    margin-right: 15px;
    margin-bottom: 10px;

    .member-avatar {
      width: 30px;
      height: 30px;
      border-radius: 50%;
      margin-right: 5px;
    }

    span {
      font-size: 14px;
    }
  }
}

/* 群聊标识样式 */
.group-indicator {
  position: absolute;
  bottom: -2px;
  right: -2px;
  background-color: #ff6d6d;
  color: white;
  font-size: 10px;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.contact-avatar {
  position: relative;
}
</style>
